package com.example.common.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


@Slf4j
public class ZipUtils {


    /**
     * 功能描述：解压
     *
     * @param zipFileDir 压缩包路径               例如："C:\\Users\\Desktop\\zipTest.zip";
     * @param outDir  解压到的目录(支持创建)     例如："C:\\Users\\Desktop\11"
     * @return 解压后所有文件路径
     * windows压缩zip文件默认为GBK编码，此处需指定编码方式为GBK
     */
    public static List<String> unZip(String zipFileDir, String outDir) {


        try {


            if (!FileUtil.exist(zipFileDir)) {
                throw new FileNotFoundException();
            }
            List<String> unZipFilePath = new ArrayList<>();
            final ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(Paths.get(zipFileDir)), Charset.forName("GBK"));
            ZipEntry entry = null;
            String filName = null;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    filName = entry.getName();
                    final File file = new File(outDir, filName);
                    // 存放文件夹不存在则新建文件夹
                    if (!file.exists()) {
                        final boolean mkdirs = file.getParentFile().mkdirs();
                    }

                    final FileOutputStream fileOutputStream = new FileOutputStream(file);
                    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                    int len = -1;
                    final byte[] bytes = new byte[1024];
                    while ((len = zipInputStream.read(bytes)) != -1) {
                        bufferedOutputStream.write(bytes, 0, len);
                    }
                    unZipFilePath.add(outDir + File.separator + filName);
                    bufferedOutputStream.close();
                    fileOutputStream.close();
                }
                zipInputStream.closeEntry();
            }
            zipInputStream.close();

            return unZipFilePath;

        }catch (Exception e){
            log.error("解压文件出错! ：",e);
            return null;
        }

    }



}
